Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Escaping `i' in a macro for -file write-

    I have a loop over all my observations to write out data in a special way. I want to specify variables to be written in a -file write- statement with local macros. So, instead of

    Code:
    file open handle using "filename.raw",write
    local N=_N
    forvalues i=1/`N' {
       file write handle var[`i']  _n
    }

    I want to replace var[i] with a local macro with the same content. I can get
    var[`i'] into a macro, but I can't use that macro. For example:

    Code:
     local mac var[\`i']
    
    . macro list _mac
    _mac:           var[`i']
    
    . di "`mac'"
    var[]
    By escaping the backquote with the backslash I get the `i' into the macro but it disappears when the macro is evaluated. Naturally, because `i' evaluates to a null string. The same thing happens in -file write-. I figured that there would be a way to escape the quotes, but putting additional backslashes in front of the backquote doesn't help. Here it is with an extra slash:

    Code:
     . local mac var[\\`i']
    
    . macro list _mac
    _mac:           var[\]
    
    . di "`mac'"
    var[\]
    So, is there a way to get the backslash into the macro definition? Any suggestions appreciated. Note that -export delimited- won't meet my needs and there would be serious support issues with requiring Python. The documentation for the escape character is on page 16 of https://www.stata.com/manuals/pmacro.pdf but it doesn't seem to address this sort of recursion.

  • #2
    Code:
    . clear*
    
    .
    . local mac var[\`i']
    
    .
    . display "`mac'" // NO GOOD
    var[]
    
    .
    . display "`macval(mac)'" // GOOD
    var[`i']

    Comment


    • #3

      Code:
      local mac = var[`i'] 
      seems to me the easiest way to proceed, but I may be missing the point. I don't think I've ever used escape characters here; just ensure that the local macro contents are defined and used when you need them.

      Comment


      • #4
        Thanks . -macval(name)- is a step to a solution. I should have seen it in the docs. However, I had hoped to make a local macro that would expand to allow multiple variables to be written:

        Code:
         file write foo (var1[`i']) ","  (var2[`i']) ..."," (varn[`i'])
        but since -macval- takes a name and not a string as its argument, there are further complications. I don't know the number of variables in advance so it looks like the only path open to me is to -file write- one variable at a time, in a loop over the variables and then write _n at the end of that inner loop. . I'll have to experiment.

        Comment

        Working...
        X